package com.ruoyi.flowable.listener;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.spring.SpringUtils;

import com.ruoyi.system.service.ISysPostService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class UserTaskListener implements TaskListener {


    @Override
    public void notify(DelegateTask delegateTask) {
        String assign = delegateTask.getAssignee();
        log.info("进入监听器:" + delegateTask.getEventName());

        if ("create".equals(delegateTask.getEventName()) &&  null != assign && assign.contains("STARTER_")){ //任务创建监听器
            Long postId = Long.parseLong(assign.substring(assign.indexOf("__")+2));
            ISysPostService postService = SpringUtils.getBean(ISysPostService.class);
            List<SysUser> sysUsers = new ArrayList<>();
            if (assign.contains("STARTER_DEPT_POST__")) {
                Long starterDeptId = (Long) delegateTask.getVariable("starterDeptId");
                //根据岗位id获取用户
                sysUsers = postService.selectUserNamesByPostIdAndDeptId(postId, starterDeptId);
            } else if (assign.contains("STARTER_POST__")) {
                //根据岗位id获取用户
                sysUsers = postService.selectUserNamesByPostId(postId);
            }

            TaskService taskService = SpringUtils.getBean(TaskService.class);
            if (sysUsers.isEmpty()) {
                log.info("没有处理人");
                taskService.setAssignee(delegateTask.getId(), "test");
            } else if (sysUsers.size() == 1) {
                log.info("一个处理人");
                taskService.setAssignee(delegateTask.getId(), sysUsers.get(0).getUserName());
            } else {
                //多个人员时候处理
                log.info("多个处理人");
                taskService.setAssignee(delegateTask.getId(), null);
                sysUsers.forEach(user -> taskService.addCandidateUser(delegateTask.getId(), user.getUserName()));
            }
        } else if ("complete".equals(delegateTask.getEventName())){ //任务完成监听器

        }
    }

}
